package com.javasm.controller;

import com.javasm.entity.User;
import com.javasm.service.LoginService;
import com.javasm.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("Utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);

        //调用service
        LoginService loginService  =  new LoginServiceImpl();
        User loginUser  =  loginService.login(username,password);

        //根据业务执行结果，做反馈
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();


        if(loginUser!= null){
            //用户名密码正确，说明登录成功！
            //把信息写入session
            HttpSession session = req.getSession();
            session.setAttribute("loginUser",loginUser);

            System.out.println("登录成功！！！！！");
            writer.println("<h1>欢迎" + loginUser.getUsername()+"登录系统</h1>" );
            writer.println("<hr>");
            writer.println("<a href='/day10/logout'>登出系统</a><br/>");
            writer.println("<hr>");
            writer.println("请使用导航菜单<br/>");
            writer.println("<a href='/day10/user'>用户系统</a><br/>");
            writer.println("<a href='/day10/prod'>商品系统</a><br/>");
            writer.println("<hr>");
        }else{
            System.out.println("登录失败！！！！！！");
            writer.println("登录失败");
            writer.println("登录失败------<script>setTimeout(()=>{ location.href='/day10/loginpage.html'},2000);</script>");
        }
        writer.close();
    }
}
